package dbb

import (
	"strings"

	"fyne.io/fyne/v2"
	"fyne.io/fyne/v2/container"
	"fyne.io/fyne/v2/data/binding"
	"fyne.io/fyne/v2/widget"
	"github.com/gogf/gf/v2/container/garray"
	octicons "github.com/lusingander/fyne-octicons"
	"github.com/y2h/fyne_poem/util"
	"github.com/y2h/fyne_poem/widgets"
)

var btnAddTbl = widget.NewButton("Add Table", func() {})
var btnDelTbl = widget.NewButton("Delete", func() {})
var treepop  *fyne.Container

func treepop1(v string) {
	if treepop == nil {
		treepop = container.NewVBox(btnAddTbl, btnDelTbl)
	}
	btnAddTbl.OnTapped = func() {
		addtbl := widget.NewEntry()
		addtbl.SetText("newtable")
		dl := binding.NewStringList()
		ga := garray.New()
		frmCol := widgets.Frmtblfield()
		frmCol.SubmitText = "Add col"
		frmCol.OnSubmit = func() {
			ga.Clear()
			ga.Append(
				frmCol.Items[0].Widget.(*widget.Entry).Text,
				frmCol.Items[1].Widget.(*widget.Entry).Text,
				frmCol.Items[2].Widget.(*widget.Select).Selected,
				frmCol.Items[3].Widget.(*widget.Check).Checked,
				frmCol.Items[4].Widget.(*widget.Entry).Text,
				frmCol.Items[5].Widget.(*widget.Entry).Text,
				frmCol.Items[6].Widget.(*widget.Entry).Text,
				frmCol.Items[7].Widget.(*widget.Entry).Text,
			)
			dl.Append(ga.String())
			Me.Msg.SetText("add col")
		}
		lst := widget.NewListWithData(dl, func() fyne.CanvasObject {
			return widget.NewLabel("No data")

		}, func(di binding.DataItem, co fyne.CanvasObject) {
			lbl := co.(*widget.Label)
			lbl.Bind(di.(binding.String))
		})
		btnAdd := widget.NewButton("Add Table", func() {
			dlv, _ := dl.Get()
			sb := strings.Builder{}
			tblnm := strings.TrimSpace(addtbl.Text)
			sb.WriteString("create table if not exists " + tblnm)
			sb.WriteString("(")
			for i, v := range dlv {
				vs := strings.Split(v, ",")
				sb.WriteString(vs[1] + " ")
				sb.WriteString(vs[2])
				if i < len(dlv)-1 {
					sb.WriteString(",")
				}
			}

			sb.WriteString(");")
			// Me.Msg.SetText(sb.String())
			_, err := Me.Db.Exec(Ctx, sb.String())
			if err != nil {
				Me.Msg.SetText(err.Error())
				return
			}
			Me.Msg.SetText("Add table successfully")

			parent.DeleteChildren(true)
			SetKi(Me.Db, Me.Name)
			RefreshDbtree()
		})
		ctnAdd := container.NewBorder(
			container.NewVBox(addtbl, btnAdd), nil, frmCol, nil,
			lst,
		)
		if strings.Contains(v, "Tables(") {
			dataBrowser := container.NewTabItemWithIcon("",
				octicons.PlussmallIcon(),
				ctnAdd)

			dataBrowser.Text = "Add Table"
			Me.Tabs.Append(dataBrowser)
			Me.Tabs.Select(dataBrowser)
		}
	}
	btnDelTbl.OnTapped = func() {
		if util.IsInSlice(v, dbs.Keys()) {
			parent.DeleteChildByName(v, true)
			dbs.Remove(v)
			Me.Msg.SetText("Delete " + v)
			RefreshDbtree()
		}
		if Me.Tbls.Contains(v) {
			_, err := Me.Db.Exec(Ctx, "drop table if exists "+v)
			if err != nil {
				Me.Msg.SetText(err.Error())
				return
			}
			Me.Msg.SetText("delete table success: " + v)
			parent.DeleteChildren(true)
			SetKi(Me.Db, Me.Name)
			RefreshDbtree()
		}
	}

}
